package com.fishbone.core.cloud.feign;

import com.fishbone.core.api.ResponseEntity;
import com.fishbone.core.api.ResultCode;
import feign.FeignException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * feign fallback 代理处理
 * @ClassName FishBoneFeignFallback
 * @Author huyaxi
 * @DATE 2020/4/24 10:32
 */
@Slf4j
@AllArgsConstructor
public class FishBoneFeignFallback<T> implements MethodInterceptor {

    private final Class<T> targetType;
    private final String targetName;
    private final Throwable cause;

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        String errorMessage = cause.getMessage();
        log.error("FishBoneFeignFallback:[{}.{}] serviceId:[{}] message:[{}]", targetType.getName(), method.getName(), targetName, errorMessage);
        Class<?> returnType = method.getReturnType();
        // 返回空
        if (ResponseEntity.class != returnType) {
            return null;
        }
        // 非FeignException
        if (!(cause instanceof FeignException)) {
            return  ResponseEntity.fail(ResultCode.INTERNAL_SERVER_ERROR,errorMessage);
        }
        FeignException exception = (FeignException) cause;
        String contentUTF8 = exception.contentUTF8();
        if(Objects.isNull(contentUTF8)){
            return  ResponseEntity.fail(ResultCode.INTERNAL_SERVER_ERROR,errorMessage);
        }
        return ResponseEntity.fail(contentUTF8);
    }
}
